package service

import (
	"context"
	"go_server/databases/mongoc"
	"go_server/models"
	"go_server/models/req"
	"go_server/models/res"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type VehicleInformation struct{}

// 添加档案信息
func (v VehicleInformation) Add(Vehicle *models.VehicleInformation, userName string) bool {
	var coll = mongoc.GetColl(Vehicle.TableName())
	Vehicle.CreatedTime = time.Now()
	Vehicle.Creator = userName
	Vehicle.State = "unaudited"
	if _, err := coll.InsertOne(context.TODO(), Vehicle); err == nil {
		return true
	} else {
		log.Panicln(err.Error())
		return false
	}
}

// 分页查询档案列表
func (v VehicleInformation) FindList(page int64, pageSize int64) ([]*res.VehicleInformationFindListRes, error) {
	Vehicle := new(models.VehicleInformation)
	var coll = mongoc.GetColl(Vehicle.TableName())
	list := make([]*res.VehicleInformationFindListRes, 0)
	findOpts := options.Find().SetLimit(pageSize).SetSkip((page - 1) * pageSize)
	cursor, err := coll.Find(context.Background(), bson.D{}, findOpts)
	if err == nil {
		for cursor.Next(context.Background()) {
			metamb := new(models.VehicleInformation)
			mb := new(res.VehicleInformationFindListRes)
			err = cursor.Decode(metamb)
			if err != nil {
				return nil, err
			}
			// 抽离需要的数据
			{
				mb.Id = metamb.ID
				mb.AffiliatedCompany = metamb.VehicleBasicInformation.AffiliatedCompany
				mb.LicensePlateNumber = metamb.VehicleBasicInformation.LicensePlateNumber
				mb.VehicleType = metamb.VehicleBasicInformation.VehicleType
				mb.VehicleManufacturer = metamb.VehicleBasicInformation.VehicleManufacturer
				mb.VehicleIdentificationNumber = metamb.VehicleBasicInformation.VehicleIdentificationNumber
				mb.OperatingCondition = metamb.VehicleBasicInformation.OperatingCondition
				mb.CreatedTime = metamb.CreatedTime
				mb.Creator = metamb.Creator
				mb.State = metamb.State
			}
			list = append(list, mb)
		}
		if err == nil {
			return list, nil
		}
	}
	return nil, err
}

// 查看详情
func (v VehicleInformation) FindDetails(id primitive.ObjectID) *models.VehicleInformation {
	vehicle := new(models.VehicleInformation)
	var coll = mongoc.GetColl(vehicle.TableName())
	Result := coll.FindOne(context.Background(), bson.D{{"_id", id}})
	err := Result.Decode(vehicle)
	if err != nil {
		return nil
	}
	return vehicle
}

// 档案审核
func (v VehicleInformation) Audit(body *req.AuditReq) bool {
	Vehicle := new(models.VehicleInformation)
	var coll = mongoc.GetColl(Vehicle.TableName())
	var state string
	if body.Audit {
		state = "approve"
	} else {
		state = "forbid"
	}
	_, err := coll.UpdateOne(context.Background(),
		bson.D{{"_id", body.Id}},
		bson.D{{"$set", bson.D{{"state", state}}}})
	return err == nil
}

// 批量审核
func (v VehicleInformation) BatchAudit(body *req.BatchAuditReq) bool {
	Vehicle := new(models.VehicleInformation)
	var coll = mongoc.GetColl(Vehicle.TableName())
	var state string
	if body.Audit {
		state = "approve"
	} else {
		state = "forbid"
	}
	filter := bson.D{{"_id", bson.D{{"$in", body.Ids}}}}
	update := bson.D{{"$set", bson.D{{"state", state}}}}
	_, err := coll.UpdateMany(context.Background(), filter, update)
	return err == nil
}

// 档案修改人及修改时间更新
func (v VehicleInformation) UpdateTimeAndPeople(userName string, id primitive.ObjectID) bool {
	Vehicle := new(models.VehicleInformation)
	var coll = mongoc.GetColl(Vehicle.TableName())
	_, err := coll.UpdateOne(context.Background(),
		bson.D{{"_id", id}},
		bson.D{{"$set", bson.D{{"updateTime", time.Now()}, {"updater", userName}}}})
	return err == nil
}

// 条件查询 *
func (v VehicleInformation) ConditionalFind(query *req.ConditionalFindReq) ([]*res.VehicleInformationFindListRes, error) {
	Vehicle := new(models.VehicleInformation)
	var coll = mongoc.GetColl(Vehicle.TableName())
	list := make([]*res.VehicleInformationFindListRes, 0)
	page := query.Page
	pageSize := query.PageSize
	findOpts := options.Find().SetLimit(pageSize).SetSkip((page - 1) * pageSize)
	// 时间范围条件
	T := make([]bson.M, 2)
	T[0] = bson.M{"createdTime": bson.M{
		"$gt": query.CreatedStartTime,
	}}
	T[1] = bson.M{"createdTime": bson.M{
		"$lt": query.CreatedEndTime,
	}}

	findFilter := bson.M{
		// "state": "approve",
		"vehicleBasicInformation.licensePlateNumber": "京A12345",
		// "$and": T,
	}
	log.Printf("findFilter: %+v\n", findFilter)
	cursor, err := coll.Find(context.TODO(), findFilter, findOpts)
	if err == nil {
		for cursor.Next(context.Background()) {
			metamb := new(models.VehicleInformation)
			mb := new(res.VehicleInformationFindListRes)
			err = cursor.Decode(metamb)
			if err != nil {
				return nil, err
			}
			// 抽离需要的数据
			{
				mb.Id = metamb.ID
				mb.AffiliatedCompany = metamb.VehicleBasicInformation.AffiliatedCompany
				mb.LicensePlateNumber = metamb.VehicleBasicInformation.LicensePlateNumber
				mb.VehicleType = metamb.VehicleBasicInformation.VehicleType
				mb.VehicleManufacturer = metamb.VehicleBasicInformation.VehicleManufacturer
				mb.VehicleIdentificationNumber = metamb.VehicleBasicInformation.VehicleIdentificationNumber
				mb.OperatingCondition = metamb.VehicleBasicInformation.OperatingCondition
				mb.CreatedTime = metamb.CreatedTime
				mb.Creator = metamb.Creator
				mb.State = metamb.State
			}
			list = append(list, mb)
		}
		if err == nil {
			return list, nil
		}
	}
	return nil, err
}

// 根据 id 删除档案
func (v VehicleInformation) DelById(id primitive.ObjectID) bool {
	vehicle := new(models.VehicleInformation)
	var coll = mongoc.GetColl(vehicle.TableName())
	coll.FindOneAndDelete(context.Background(), bson.M{"_id": id})
	return true
}
